<?php
require_once 'library/Database.php';
$forecast = new Database();
if (Session::tokenExist()) {
    header('Location: dashboard.php');
    exit;
}

$errormsg = '';
if (isset($_POST['login'])) {
    unset($_POST['login']);
    $isValid = $forecast->validate($_POST);
    if ($isValid === true) {
        $found = $forecast->authenticate('users', $_POST);
        if (is_object($found)) {
            Session::set('sessionToken', $found->username);
            Session::set('username', $found->username);
            Session::set('sid', $found->id);
            header('Location: dashboard.php');
            exit;
        } else {
            $errormsg = 'Could NOT find this credentials in the database';
        }
    }
    else {
        foreach ($isValid as $key => $error) {
            $errormsg .= $error . '<br />';
        }
    }
}


?>

<!DOCTYPE html>
<!--[if IE 8]>
<html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en"> <!--<![endif]-->

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width"/>
    <title>forecasting enrollment system</title>

    <link rel="stylesheet" href="css/normalize.css"/>

    <link rel="stylesheet" href="css/foundation.css"/>
    <link rel="stylesheet" href="css/overrides.css"/>


    <script src="js/vendor/custom.modernizr.js"></script>

</head>
<body>

<div class="row">
    <div class="large-12 columns text-center">
        <h2 class="login-header">forecasting enrollment system</h2>

        <?php if (!empty($errormsg)) { ?>
            <div class="alert-box alert radius">
                <?php echo $errormsg; ?>
                <a href="" class="close">×</a>
            </div>
        <?php } ?>
        <hr/>
        <div class="small-4 columns large-centered panel">
            <form action="./" method="post" class="login-form">
                <label>Username</label>
                <input type="text" required="required" name="username" placeholder="Username">
                <label>Password</label>
                <input type="password" required="required" name="password" placeholder="Password">
                <input type="submit" name="login" value="Login" class="button success radius">
            </form>
        </div>

    </div>
</div>

<div class="row">
    <div class="large-8 columns">



    </div>

    <div class="large-4 columns">

    </div>
</div>

<script>
    document.write('<script src=' +
            ('__proto__' in {} ? 'js/vendor/zepto' : 'js/vendor/jquery') +
            '.js><\/script>')
</script>

<script src="js/foundation.min.js"></script>
<script>
    $(document).foundation();
</script>
</body>
</html>
